package com.testdocs.client.project.create;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.testdocs.client.ClientFactory;
import com.testdocs.client.project.ProjectInfo;
import com.testdocs.client.project.ProjectService;
import com.testdocs.client.project.ProjectServiceAsync;
import com.testdocs.client.project.dashboard.DashboardPlace;
import com.testdocs.client.project.event.ProjectCreatedEvent;
import com.testdocs.client.project.event.ProjectDeselectedEvent;
import com.testdocs.client.project.event.ProjectSelectedEvent;
import com.testdocs.client.project.i18n.ProjectConstants;
import com.testdocs.client.validation.ConstraintViolationException;
import com.testdocs.client.validation.SelfValidating;
import com.testdocs.client.version.VersionInfo;

public class CreateProjectActivity extends AbstractActivity
		implements CreateProjectView.Presenter {
	private ClientFactory clientFactory;

	public CreateProjectActivity(ClientFactory factory) {
		this.clientFactory = factory;
	}
	
	@Override
	public void start(AcceptsOneWidget panel, EventBus eventBus) {
		clientFactory.getEventBus().fireEvent(new ProjectDeselectedEvent());
		CreateProjectView view = clientFactory.getCreateProjectView();
		view.setPresenter(this);
		view.clearForm();
		panel.setWidget(view);		
	}

	@Override
	public ProjectInfo doCreate(String projectName, String versionName) throws ConstraintViolationException {
		ProjectConstants createProjectConstants = (ProjectConstants) GWT.create(ProjectConstants.class);
		
		ProjectInfo projectInfo = new ProjectInfo();
		projectInfo.setName(projectName);
		VersionInfo versionInfo = new VersionInfo();
		versionInfo.setName(versionName);
		
		clientFactory.getValidator().validate(new SelfValidating[]{projectInfo, versionInfo});
		
		clientFactory.getWaitingPopupPanel().show(createProjectConstants.creatingProjectStatus());
	    ProjectServiceAsync projectService = GWT.create(ProjectService.class);
	    projectService.createProject(projectInfo, versionInfo, new AsyncCallback<ProjectInfo>() {
	    	public void onFailure(Throwable error) {
				clientFactory.getRpcErrorHandler().handle(error);
				clientFactory.getWaitingPopupPanel().hide();
	    	}

	    	public void onSuccess(ProjectInfo result) {
	    		clientFactory.getWaitingPopupPanel().hide();
	    		clientFactory.getEventBus().fireEvent(new ProjectCreatedEvent(result));
	    		clientFactory.getEventBus().fireEvent(new ProjectSelectedEvent(result));
				clientFactory.getPlaceController().goTo(new DashboardPlace(result.getProjectId()));
	    	}
	    });
		return null;
	}
}
